package com.seckill.admin.controller;

import com.seckill.admin.dto.AdminLogin;
import com.seckill.admin.pojo.Admin;
import com.seckill.admin.service.AdminService;
import com.seckill.util.JwtTokenUtil;
import com.seckill.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 控制器</p>
 *
 * @author 作者
 * @since 2022-03-09
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;


    /***
     * 根据ID查询User数据
     * @return
     */
    @PostMapping("/login")
    public Result<Admin> findById(@Valid @RequestBody AdminLogin adminLogin) throws Exception {
        //调用UserService实现根据主键查询User
        Admin admin = adminService.findByName(adminLogin.getUsername());
        if(admin==null){
            return Result.error("账号不存在");
        }

        if(!admin.getPassword().equals(adminLogin.getPassword())){
            return Result.error("密码错误");
        }

        //登录成功，生成令牌
        Map<String,Object> payload = new HashMap<String,Object>();
        payload.put("username",admin.getLoginName());
        payload.put("key","seckill");

        //生成令牌
        String jwt = JwtTokenUtil.generateTokenAdmin(UUID.randomUUID().toString(),payload, 900000000L);
        return Result.ok(jwt);
    }
}

